<template>
  <div class="relative page-container give-car-wrapper">
    <div class="page-form-block">
      <summary-info :summaryList="summaryLease" />
    </div>
    <a-divider />
    <page-form :model="form" layout="vertical" :rules="rules" ref="formRef">
      <card title="续租信息">
        <page-form-row>
          <page-form-item field="endTime" label="续租后还车时间">
            <template #label-extra>
              <div class="rent-days"> 续租时长：{{ form.rentDays || '- 天' }} </div>
            </template>
            <!-- <i-date-picker
              :disabledDate="disabledDate"
              v-model="form.endTime"
              :show-now-btn="false"
              @change="changeTimeFn"
              style="width: 280px"
            /> -->
            <i-date-picker
              :disabledDate="disabledDate"
              class="w-full"
              :show-now-btn="false"
              v-model="form.endTime"
              value-format="YYYY-MM-DD"
              @change="changeTimeFn"
            />
          </page-form-item>
          <page-form-item label="续租周期">
            <i-separate-range-picker v-model="rentTimeRange" class="w-full" disabled />
            <!-- <a-range-picker class="w-full" v-model="rentTimeRange" disabled style="width: 280px" /> -->
          </page-form-item>

          <page-form-item label="续租备注" size="2/3">
            <i-textarea v-model="form.remark" />
          </page-form-item>
        </page-form-row>
      </card>
      <!-- 合同信息 -->
      <contract-card />
      <!-- 费用信息 -->
      <div class="relative fee-pane-content">
        <page-form :model="feeForm" ref="feeFormRef" layout="vertical">
          <card toggle>
            <template #title>续租费用</template>
            <template v-for="(item, index) in feeForm.orderFee" :key="index">
              <fee-pane
                :isReletOrder="true"
                :orderFormType="'reletOrder'"
                :orderFeeIndex="index"
                :disabledOnlineFee="orderInfo.orderSource == 1"
                :prevFeeForm="prevFeeForm"
                @feeChange="feeChangeFn"
              />
            </template>
          </card>
        </page-form>
      </div>
      <!-- 账单收款分期计划 -->
      <order-payment-pane v-if="feeRealtimeSum > 0 && form.rentMonths > 0" :contractAmount="feeRealtimeSum" />
    </page-form>
  </div>
  <!-- 二次确认 -->
  <a-modal title="提示" v-model:visible="confirmVisible">
    <div v-for="(it, i) in resultMsg" :key="i">{{ it }}</div>
    <div>请确认是否排车？</div>
    <template #footer>
      <a-button @click="confirmVisible = false">关闭</a-button>
      <a-button type="primary" @click="confirmSubmit">确认</a-button>
    </template>
  </a-modal>
  <!-- 底部 footer -->
  <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
</template>
<script setup name="LongOrderReletOrder">
  import { ref, provide, computed, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import { computeRentDay, getLongOrderDetails, reletOrder, getLongOrderFeeDetail, calcPrice } from '@/api/order/czsOrder'
  import feePane from './components/order-fee/fee-pane.vue'
  import iTextarea from '@/views/order/long-order/components/i-textarea.vue'
  import {
    buildCostInfoParam,
    initFeeDetail,
    getStoreTemplateDetail,
    handleStoreTemplateDetail,
    handleAddserviceDefaultFee,
  } from './components/order-fee/fee-utils.js'
  import { platoonCarCheck } from '@/api/asset/carStock'
  import useNavigate from '@/hooks/useNavigate'
  import summaryInfo from './components/summary-info.vue'
  import contractCard from './components/contract/contract-card.vue'
  import { handleContracList } from './utils'
  import orderPaymentPane from './components/order-payment-pane.vue'
  import { decimalAddition } from '@/utils'
  import { buildTreeData, processTreeData } from './components/order-fee/fee-statistic.js'
  import { Notification } from '@arco-design/web-vue'
  import dayjs from 'dayjs'
  import useUserStore from '@/store/modules/user'

  const { navigateBack } = useNavigate()
  const userStore = useUserStore()
  const route = useRoute()
  const orderId = route.params.id
  const orderInfo = ref({})

  const form = ref({
    id: orderId,
    // 默认选中分期
    paymentScheme: 1,
    // 默认分期方式
    paymentMethod: 2,
    // 首期付款日默认值
    lnstalmentFirstDate: dayjs().format('YYYY-MM-DD'),
    // 上传合同
    contractList: [
      {
        contractFileId: '',
        contractNo: '',
        contractType: 3,
        contractTypeName: '续租合同',
        contractName: '',
        status: 'edit',
      },
    ],
  })
  // 续租周期
  const rentTimeRange = ref([])
  // 原费用信息
  const prevFeeForm = ref({})

  // 费用变化
  const feeChangeFn = (item, val, index) => {
    if ((val || val == 0) && val != '') {
      let feeDetailList = feeForm.value.orderFee[0].feeDetailList
      let option = feeDetailList[index].childrenList
      let itemName = item.itemName
      if (itemName == '月租价（标准）') {
        let target = option.find((item) => item.itemName == '车辆租金')
        if (target) target.amount = val * calcRate.value
      }
      if (itemName == '手续费（标准）') {
        let target = option.find((item) => item.itemName == '手续费')
        if (target) target.amount = val * 1
      }
      if (itemName == '基础保险（标准）') {
        let target = option.find((item) => item.itemName == '基础保险')
        if (target) target.amount = val * calcRate.value
      }
    }
  }
  // 处理默认值
  // 租赁周期限制最小时长 60 分钟
  const timeRangeValidator = (value, callback) => {
    if (value) {
      let start = dayjs(orderInfo.value.expectedReturnCarTime).add(1, 'day').format('YYYY-MM-DD 00:00:00')
      let end = dayjs(value).format('YYYY-MM-DD 23:59:59')
      if (start && end) {
        let diff = dayjs(end).diff(dayjs(start))
        console.log(start, end, diff, '12222222222222')
        if (diff < 23 * 59 * 59 * 1000) {
          callback('续租时长最短为1天')
        }
      }
    }
    callback()
  }

  const rules = {
    endTime: [{ required: true, message: '请选择续租后还车时间' }, { validator: timeRangeValidator }],
  }
  const formRef = ref()
  provide('form', form)

  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      [
        {
          label: '预计租赁周期',
          value: orderInfoVal.expectedUseCarTime
            ? `${dayjs(orderInfoVal.expectedUseCarTime).format('YYYY-MM-DD')} - ${dayjs(orderInfoVal.expectedReturnCarTime).format(
                'YYYY-MM-DD'
              )}`
            : '-',
        },
        { label: '租期', value: orderInfoVal.leaseNumberStr },
        { label: '订单来源', value: orderInfoVal.orderSourceName },
      ],
      [
        { label: '订单获取方式', value: orderInfoVal.orderAcquisitionTypeName },
        { label: '车型', value: orderInfoVal.originalModelName },
        { label: '交车车型', value: orderInfoVal.modelName },
      ],
      [{ label: '交车车牌号', value: orderInfoVal.licenseNo }],
    ]
  })

  const priceTemplateId = ref()
  const feeFormRef = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee'],
      },
    ],
  })
  provide('feeForm', feeForm)
  // 实时费用信息开始
  const feeRealtimeSum = computed(() => {
    let orderFee = feeForm.value.orderFee
    if (orderFee) {
      let feeVal = buildTreeData(orderFee)
      let feeTreeStData = processTreeData(feeVal)
      let sum = 0
      feeTreeStData.forEach((item) => {
        sum = decimalAddition(sum, item.value)
      })
      return sum
    }
    return 0
  })
  const releContractList = ref([])
  const cacheStoreTemplate = ref({})
  if (orderId) {
    getLongOrderDetails({ id: orderId }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo
      // 处理默认值
      // 车务专员 | 当前登录者 id
      form.value.returnStaffId = orderInfo.value.returnStaffId || userStore.userId
      // 初始化 endTime
      let endTime = orderInfo.value.expectedReturnCarTime
      if (endTime) {
        form.value.endTime = dayjs(endTime).add(1, 'day').format('YYYY-MM-DD 23:59:59')
        changeTimeFn(form.value.endTime)
      }

      // 读取门店模板配置
      getStoreTemplateDetail(orderInfo.value.siteId, 2, (storeTemplate, templateId) => {
        cacheStoreTemplate.value = storeTemplate
        let feeValue = feeForm.value
        initFeeDetail(feeValue, storeTemplate)
        // 更新费用模板 id
        priceTemplateId.value = templateId
        // 初始化费用
        setDefaultFee()
      })
      // 合同信息处理
      let orderContractList = orderInfo.value.contractList
      if (orderContractList && orderContractList.length > 0) {
        releContractList.value = orderContractList.filter((item) => item.contractTypeName.indexOf('续租') !== -1)

        if (releContractList.value.length == 0 || releContractList.value.every((item) => item.contractFileId)) {
          releContractList.value.push({
            contractFileId: '',
            contractNo: '',
            contractType: 3,
            contractTypeName: `续租合同${releContractList.value.length + 1}`,
            contractName: '',
            status: 'edit',
          })
        }
      }
      console.log(releContractList.value, 'releContractList.value,121')
      form.value.contractList = handleContracList(releContractList.value)
      rentTimeRange.value = [
        dayjs(orderInfo.value.expectedReturnCarTime).add(1, 'day').format('YYYY-MM-DD'),
        form.value.endTime && form.value.endTime.substring(0, 10),
      ]
    })

    // 获取原费用信息
    getLongOrderFeeDetail({ id: orderId }).then((res) => {
      const result = res.result
      const orderFeeList = result.orderFeeList
      if (orderFeeList?.length > 0) {
        let rentFee = orderFeeList.find((item) => item.feeNameId == 1)
        prevFeeForm.value = {
          randomKey: 0,
          orderFee: [
            {
              // 费用类型（线上费用|线下费用）
              feeDetailList: [],
              feeDetailTypeList: ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee'],
            },
          ],
        }
        // 创建费用时的费用模板快照
        let priceTemplateSnapshot = rentFee.priceTemplateSnapshot
        // 解析后的费用模板
        let storeTemplate = null
        if (priceTemplateSnapshot) {
          priceTemplateSnapshot = JSON.parse(priceTemplateSnapshot)
          storeTemplate = handleStoreTemplateDetail(priceTemplateSnapshot)
        }
        initFeeDetail(prevFeeForm.value, storeTemplate)
        // 回显
        // 默认费用
        let feeDetailList = rentFee.feeDetailList
        let formfeeDetailList = prevFeeForm.value.orderFee[0].feeDetailList
        formfeeDetailList.forEach((formFeeDetailItem) => {
          let findResult = feeDetailList.find((item) => {
            let sameFeeCategory = item.feeCategory == formFeeDetailItem.feeCategory
            let sameFeeName = item.itemName == formFeeDetailItem.feeName
            return sameFeeCategory || sameFeeName
          })
          if (findResult) {
            formFeeDetailItem.categoryType = findResult.type
          } else {
            formFeeDetailItem.categoryType = 0
          }
          formFeeDetailItem.childrenList?.forEach((item) => {
            let findFeeDetail = findResult?.childrenList.find((feeDetailItem) => feeDetailItem.itemName == item.itemName)
            if (!findFeeDetail) {
              findFeeDetail = feeDetailList.find((feeDetailItem) => feeDetailItem.itemName == item.itemName)
            }
            if (findFeeDetail) {
              item.amount = findFeeDetail.amount
              item.id = findFeeDetail.id
              item.statics = true
            }
          })
        })
      }
    })
  }

  // 获取默认费用
  // 车型价格模板 id
  // const priceModelId = ref()
  const calcRate = ref()
  const setDefaultFee = () => {
    let startTime = orderInfo.value.expectedReturnCarTime
    const param = {
      startTime: dayjs(startTime).add(1, 'day').format('YYYY-MM-DD 00:00:00'),
      id: form.value.id,
      siteId: orderInfo.value.siteId,
      modelId: orderInfo.value.originalModelId,
      endTime: dayjs(form.value.endTime).format('YYYY-MM-DD 23:59:59'),
      type: 3,
    }
    calcPrice(param).then((res) => {
      const { basePrice, otherPrice, rate } = res.result
      calcRate.value = rate
      // priceModelId.value = basePrice.id
      let feeValue = feeForm.value
      let feeDetailList = feeValue.orderFee[0].feeDetailList
      // 处理增值服务费默认值，配置用户自定义费用时，按次|按日收费，此处rate为后端返回的单位天，用于计算按天计费费用
      handleAddserviceDefaultFee(feeDetailList, cacheStoreTemplate.value, rate)
      // 初始化其他费用
      feeDetailList.forEach((feeCategory) => {
        const { childrenList } = feeCategory
        // 默认系统计算的费用包含，基础费用，押金费用以及增值服务费中的例如上门取车费、夜间服务费等费用
        if (childrenList && childrenList.length > 0) {
          childrenList.forEach((feeItem) => {
            // 费用名称
            let feeName = feeItem.itemName
            // basicPrice 费用
            if (feeName == '月租价（标准）') {
              if (basePrice?.price >= 0) feeItem.amount = basePrice?.price
            }
            if (feeName == '手续费') {
              if (basePrice?.poundageAmount >= 0) feeItem.amount = basePrice?.poundageAmount
            }
            if (feeName == '手续费（标准）') {
              if (basePrice?.poundageAmount >= 0) feeItem.amount = basePrice?.poundageAmount
            }
            if (feeName == '基础保险（标准）') {
              if (basePrice?.insuranceAmount >= 0) feeItem.amount = basePrice?.insuranceAmount
            }
            // otherPrice 费用
            if (otherPrice && otherPrice.length > 0) {
              let findIndex = otherPrice.findIndex((item) => item.itemName == feeName)
              if (findIndex >= 0) {
                let fee = otherPrice[findIndex]
                feeItem.statics = true
                if (fee?.amount >= 0) {
                  feeItem.amount = fee.amount
                }
              }
            }
          })
        }
      })
      // 当没有下单车型时，此时费用计算不会计算出下述几种费用，此时需要手动补充费用，补充0
      if (!basePrice) {
        feeDetailList.forEach((feeCategory) => {
          const { childrenList } = feeCategory
          if (childrenList && childrenList.length > 0) {
            childrenList.forEach((feeItem) => {
              // 费用名称
              let feeName = feeItem.itemName
              // basicPrice 费用
              if (['月租价（标准）', '车辆租金', '手续费（标准）', '手续费', '基础保险', '基础保险（标准）'].includes(feeName)) {
                feeItem.amount = 0
              }
            })
          }
        })
      }
    })
  }

  // disabled Date|Time
  const disabledDate = (dateVal) => {
    let expectedReturnCarTime = orderInfo.value.expectedReturnCarTime
    const prevDate = dayjs(expectedReturnCarTime).add(1, 'day').format('YYYY-MM-DD 00:00:00')
    if (!dateVal || !prevDate) {
      return false
    }
    // 存在限制最大范围
    // 当前时间是 23:50
    if (dayjs(prevDate).hour() == 23 && dayjs(prevDate).minute() == 59) {
      return dayjs(prevDate).add(1, 'd').startOf('day').valueOf() > dayjs(dateVal).valueOf()
    } else {
      return dayjs(prevDate).startOf('day').valueOf() > dayjs(dateVal).valueOf()
    }
  }

  const changeTimeFn = (value) => {
    let startTime = orderInfo.value.expectedReturnCarTime
    if (value) {
      // 计算租期
      const param = {
        expectedUseCarTime: dayjs(startTime).add(1, 'day').format('YYYY-MM-DD 00:00:00'),
        expectedReturnCarTime: dayjs(value).format('YYYY-MM-DD 23:59:59'),
      }
      computeRentDay(param).then((res) => {
        let { dateStr, months } = res.result
        form.value.rentDays = dateStr
        form.value.rentMonths = months
        // form.value.paymentScheme = months < 1 ? 1 : 2
      })
      setDefaultFee()
      rentTimeRange.value = [
        dayjs(orderInfo.value.expectedReturnCarTime).add(1, 'day').format('YYYY-MM-DD'),
        form.value.endTime && form.value.endTime.substring(0, 10),
      ]
    } else {
      form.value.rentDays = undefined
    }
  }
  // 排车校验
  const resultMsg = ref([])
  const confirmVisible = ref(false)
  const platoonCarVerify = (callback) => {
    let startTime = orderInfo.value.expectedReturnCarTime
    const params = {
      refId: orderInfo.value.id,
      startTime: dayjs(startTime).add(1, 'day').format('YYYY-MM-DD 00:00:00'),
      endTime: dayjs(form.value.endTime).add(1, 'day').format('YYYY-MM-DD 23:59:59'),
      useType: 3,
      carId: orderInfo.value.carId,
    }
    platoonCarCheck(params).then((res) => {
      let msgList = res.result.resultMsg || []
      if (msgList.length) {
        resultMsg.value = msgList
        confirmVisible.value = true
        return
      }
      callback && callback()
    })
  }
  // 续租
  const reletFn = () => {
    let feeFormValue = feeForm.value
    let costInfo = buildCostInfoParam(feeFormValue)
    form.value.endTime = dayjs(form.value.endTime).format('YYYY-MM-DD 23:59:59')
    const param = {
      ...form.value,
      orderFee: costInfo.orderFee[0],
    }

    param.contractAmount = feeRealtimeSum.value
    let contractList = form.value.contractList
    param.contractFileId = contractList[0].fileId
    param.contractNo = contractList[0].contractNo
    param.contractName = contractList[0].contractName
    if (feeRealtimeSum.value <= 0 || form.value.rentMonths <= 0) {
      param.paymentScheme = 1
    }
    okLoading.value = true
    reletOrder(param)
      .then(() => {
        confirmVisible.value = false
        Notification.success({
          content: '续租成功',
          closable: true,
          duration: 3000,
        })
        navigateBack()
      })
      .finally(() => (okLoading.value = false))
  }
  // 二次询问确认
  const confirmSubmit = () => {
    reletFn()
  }
  const okLoading = ref(false)
  const submitFn = () => {
    formRef.value.validate((error) => {
      if (!error) {
        feeFormRef.value.validate((error) => {
          if (!error) {
            platoonCarVerify(() => {
              reletFn()
            })
          }
        })
      }
    })
  }

  const loadData = () => {}

  onMounted(() => {
    loadData()
  })
</script>
<style lang="less" scoped>
  :deep(.arco-card) {
    background-color: inherit;
  }
  .order-summary-pane {
    :deep {
      .field-label {
        width: 200px;
        display: inline-block;
        text-align: right;
      }
    }
  }
  .rent-days {
    color: rgb(var(--primary-6));
  }
  .contContainer {
    margin-top: 25px;
    .item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
    }
  }
</style>
